﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Pickle.Core.ExtensionMethods;

namespace Web.Controls
{
	public partial class NavigationMenu : System.Web.UI.UserControl
	{
		protected void Page_PreRender(object sender, EventArgs e)
		{
			if (IsPostBack == false)
				LoadMenu();

			SelectMenuItem();
		}

		private void SelectMenuItem()
		{
			MenuItem MI = NavMenu.Items.All()
				.Where(m => m.ValuePath == Request.QueryString["MenuItem"])
				.SingleOrDefault();

			if (MI != null)
			{
				if (MI.Depth != 0)
					MI.Parent.Selected = true;
				else
					MI.Selected = true;
			}
		}

		void LoadMenu()
		{
			for (int TopLevel = 0; TopLevel < 5; TopLevel++)
			{
				MenuItem Root = this.CreateMenuItem(TopLevel.ToString());

				NavMenu.Items.Add(Root);
				Root.NavigateUrl = this.MenuItemNavigateUrl(Root.ValuePath);

				for (int NestedLevel = 1000; NestedLevel < 1003; NestedLevel++)
				{
					MenuItem Nested = this.CreateMenuItem(NestedLevel.ToString());

					Root.ChildItems.Add(Nested);

					Nested.NavigateUrl = this.MenuItemNavigateUrl(Nested.ValuePath);
				}
			}
		}

		string MenuItemNavigateUrl(string valuePath)
		{
			if (string.IsNullOrEmpty(Request.Url.Query) == true)
				return string.Format("{0}?MenuItem={1}", Request.Url.AbsolutePath, valuePath);
			else
				if (Request.Url.Query.Contains("MenuItem=") == true)
					return string.Format("{0}{1}MenuItem={2}", Request.Url.AbsolutePath
						, Request.Url.Query.Substring(0, Request.Url.Query.IndexOf("MenuItem=")), valuePath);
				else
					return string.Format("{0}{1}&MenuItem={2}", Request.Url.AbsolutePath
						, Request.Url.Query, valuePath);
		}

		MenuItem CreateMenuItem(string value)
		{
			MenuItem MI = new MenuItem();

			MI.Value = value;
			MI.Text = "Item - " + value;

			return MI;
		}
	}
}